package com.plusjun.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plusjun.common.utils.PageUtils;
import com.plusjun.common.utils.Query;
import com.plusjun.common.utils.R;
import com.plusjun.gulimall.product.dao.SkuInfoDao;
import com.plusjun.gulimall.product.entity.SkuImagesEntity;
import com.plusjun.gulimall.product.entity.SkuInfoEntity;
import com.plusjun.gulimall.product.entity.SpuInfoDescEntity;
import com.plusjun.gulimall.product.feign.SeckillFeignService;
import com.plusjun.gulimall.product.service.*;
import com.plusjun.gulimall.product.vo.SeckillInfoVO;
import com.plusjun.gulimall.product.vo.SkuItemSaleAttrVO;
import com.plusjun.gulimall.product.vo.SkuItemVO;
import com.plusjun.gulimall.product.vo.SpuItemAttrGroupVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Resource
    SkuImagesService imagesService;
    @Resource
    SpuInfoDescService spuInfoDescService;
    @Resource
    AttrGroupService attrGroupService;
    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private SeckillFeignService seckillFeignService;
    @Resource
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max:
         */
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");

        if (StringUtils.isNotEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(key)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {

            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    /**
     * 使用异步编排
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVO item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVO skuItemVO = new SkuItemVO();
        // 使用异步编排，查询完 info信息就查询需要依赖info的
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1、sku基本信息获取：psm_sku_info
            SkuInfoEntity info = getById(skuId);
            skuItemVO.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> saleAttrfuture = infoFuture.thenAcceptAsync((res) -> {
            // 3、获取spu销售属性：
            List<SkuItemSaleAttrVO> saleAttrVOs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVO.setSaleAttr(saleAttrVOs);
        }, executor);

        CompletableFuture<Void> despfuture = infoFuture.thenAcceptAsync((res) -> {
            // 4、获取spu商品的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVO.setDesp(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> baseAttrfuture = infoFuture.thenAcceptAsync((res) -> {
            // 5、获取spu规格参数信息
            List<SpuItemAttrGroupVO> spuItemAttrGroupVOS = attrGroupService.getAttrGroupWithSpuId(res.getSpuId(), res.getCatalogId());
            skuItemVO.setGroupAttrs(spuItemAttrGroupVOS);
        }, executor);


        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // 2、sku图片信息： psm_sku_images，不需要等待别的任务
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVO.setImages(images);
        }, executor);
        // 远程查询当前sku是否参与秒杀优惠
        CompletableFuture<Void> seckillFutureTask = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.skuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillInfoVO data = (SeckillInfoVO) r.getData(new TypeReference<SeckillInfoVO>() {
                });
                if (data != null) {
                    skuItemVO.setSeckillInfo(data);
                }
            }
        }, executor);

        // 等待所有任务都完成
        CompletableFuture.allOf(saleAttrfuture, despfuture, baseAttrfuture, imageFuture,seckillFutureTask).get();

        return skuItemVO;
    }

    @Override
    public Map<Long, BigDecimal> getNewPrice(List<Long> skuIds) {
        List<SkuInfoEntity> list = this.baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuIds));
        Map<Long, BigDecimal> collect = list.stream().collect(Collectors.toMap(item1 -> item1.getSkuId(), item1 -> item1.getPrice()));
        return collect;
    }

    /**
     * 常规的编写业务
     *
     * @param skuId
     * @return
     */
    public SkuItemVO itemOld(Long skuId) {
        SkuItemVO skuItemVO = new SkuItemVO();
        // 1、sku基本信息获取：psm_sku_info
        SkuInfoEntity info = getById(skuId);
        skuItemVO.setInfo(info);


        // 2、sku图片信息： psm_sku_images
        List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
        skuItemVO.setImages(images);

        Long catalogId = info.getCatalogId();
        Long spuId = info.getSpuId();
        // 3、获取spu销售属性：
        List<SkuItemSaleAttrVO> saleAttrVOs = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
        skuItemVO.setSaleAttr(saleAttrVOs);
        // 4、获取spu商品的介绍
        SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
        skuItemVO.setDesp(spuInfoDescEntity);
        // 5、获取spu规格参数信息
        List<SpuItemAttrGroupVO> spuItemAttrGroupVOS = attrGroupService.getAttrGroupWithSpuId(spuId, catalogId);
        skuItemVO.setGroupAttrs(spuItemAttrGroupVOS);


        return skuItemVO;
    }

}